package ar.edu.itba.tp1.tpmariano;

import ar.edu.itba.tp1.gps.api.GPSState;

public class Heuristic3Problem extends Problem {

	@Override
	public Integer getHValue(GPSState state) {
		Grid grid = (Grid)state;
		int HValue = 24;
		
		for (int i=0; i < LENGTH; i++)
			for (int j=0; j < LENGTH; j++){
				char t1 = grid.getTile(i, j);
				if (i != LENGTH-1 && j != LENGTH-1){
					if (checkUpperDiamond(t1, grid.getTile(i, j+1)))
						HValue--;
					if (checkRightDiamond(t1, grid.getTile(i+1, j)))
						HValue--;
				} else if (i == LENGTH-1 && j != LENGTH-1){
					if (checkUpperDiamond(t1, grid.getTile(i, j+1)))
						HValue--;					
				} else if (i != LENGTH-1 && j == LENGTH-1){
					if (checkRightDiamond(t1, grid.getTile(i+1, j)))
						HValue--;					
				}
			}
		
		return HValue;				
	}
	
	private boolean checkUpperDiamond(char t1, char t2){
		byte north = (byte) ((t1 >> 12) & 0xF);
		byte south = (byte) ((t2 >> 4) & 0xF);
		
		return north == south;
	}
	
	private boolean checkRightDiamond(char t1, char t2){
		byte east = (byte) ((t1 >> 8) & 0xF);
		byte west = (byte) (t2 & 0xF);
		
		return east == west;
	}
	
}
